<script src="../../js/common.js"></script>
<template>
  <header>
    <div class="header-msg fs-12">
      <div class='platform-info'>
        <div class="platform-img"><img src="../../../static/img/header/logoWhite.png" alt=""></div>
        <div class="paltform-name">中国电梯质量安全服务平台</div>
      </div>
      <div class="user-box">
        <div class="user-info">
          <el-popover ref="popover1" placement="bottom" width="255" trigger="hover">
            <div class="account-box">
              <p class="account-operate"><span>账户信息</span><span @click="dialogUserInfoFormVisible = true">账户设置</span>
              </p>
              <div class="account-info">
                <ul>
                  <li class="blue-cir"><span>所在机构 : {{companyName}}</span></li>
                  <li class="yellow-cir"><span>用户角色 : {{role}}</span></li>
                  <li class="green-cir"><span>本次登录 : {{loginTime}}</span></li>
                  <!--<li class="purple-cir"><span>上次登录 : {{lastLoginTime}}</span></li>-->
                </ul>
              </div>
            </div>
          </el-popover>
          <el-button type="text" v-popover:popover1>
            <div class="user-icon"><img src="../../../static/img/logo.jpg" alt=""></div>
            <div class="user-level">{{username}}</div>
          </el-button>
          <!--账户设置弹窗-->
        </div>
        <div class="notice-box">
          <el-tooltip class="item" effect="dark" content="通知信息" placement="bottom-end">
            <el-button type="text" @click="showMsg">
              <div class="notice-icon"><img src="../../../static/img/header/ling.png" alt=""></div>
              <i class="notice-num" v-if="unReadNum!==0">{{unReadNum}}</i>
            </el-button>
          </el-tooltip>
        </div>
        <el-tooltip class="item logoutBtn" effect="dark" content="退出登录" placement="bottom-end">
          <el-button type="text" @click="loginout">
            <img class="exit-button" src="/static/img/header/exit.png" alt="">
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <el-dialog class="edit-info-dialog" :visible.sync="dialogUserInfoFormVisible" title="修改账户密码:">
      <div class="edit-info-box">
        <!--修改用户信息~头像-->
        <!--<div class="info-img">-->
        <!--<div class="head-icon">-->
        <!--<img v-if="myForm.image" :src="myForm.image" class="has-img">-->
        <!--<i v-else class="has-no-img">-->
        <!--<img src="/static/img/header/userIcon.png"/>-->
        <!--</i>-->
        <!--</div>-->
        <!--<el-upload class="upload-btn" :action=actionUrl :show-file-list="false" :on-success="handleUpImgStatus">-->
        <!--<el-button size="small" type="primary">上传头像</el-button>-->
        <!--</el-upload>-->
        <!--</div>-->
        <el-form class="info-form" status-icon ref="myForm" :model="myForm" :rules="rules" label-width="100px"
                 size="medium">
          <el-form-item label="旧密码:" prop="originalPwd">
            <el-input type="password" v-model="myForm.originalPwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码:" prop="newPwd">
            <el-input type="password" v-model="myForm.newPwd"></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="confirmPwd">
            <el-input type="password" v-model="myForm.confirmPwd"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserInfoFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm('myForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-dialogDrag ref="dialog__wrapper" custom-class="msg-dialog" :visible.sync="dialogMsgFormVisible"
               width=50% top='5vh' title="消息通知:" :show-close=false>
      <div class="dialog-body">
        <div class="line" v-dialogDragWidth="$refs.dialog__wrapper"></div>
        <div class="close-dialog">
          <img :src=closeSrc @mouseenter="closeEnter" @mouseleave="closeLeave" @click="dialogMsgFormVisible = false"/>
        </div>
        <div class="msg-box">
          <div v-if="noMsg" class="no-msg">{{noMsgText}}</div>
          <div v-else class="msg-content">
            <div class="msg-header">
              <div>
                <el-checkbox v-model="msgAlCheck" @change="msgCheckAll">全部标记已读</el-checkbox>
              </div>
              <div>
                <span><i class="unread-msg">未读{{unReadNum}}</i> / 全部{{allMsgNum}}</span>
              </div>
            </div>
            <div class="msg-main">
              <div class="msg-show" :class="index === openIndex ? 'open': ''" v-for="(item, index) in msgList">
                <div class="msg-item">
                  <div class="item-content" @click="readMsg(index, item.messageId, item.readstate)"
                       :class="item.readstate===1 ? 'has-read': ''">
                    <div class="msg-head">
                      <span class="msg-title"><b>{{item.messageType}}</b></span>
                      <span class="msg-date">{{item.createTime}}</span>
                    </div>
                    <div class="msg-text">{{item.content}}</div>
                  </div>
                  <div class="msg-coll" :class="index === openIndex ? openObj: ''">
                    {{item.content}}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="pageBar">
          <pageBar :pageObj=msgPageObj v-on:changeSearchPageNo="changePageNo"></pageBar>
        </div>
      </span>
    </el-dialog>
  </header>
</template>

<script>
  import com from '../../js/common'
  import md5 from 'js-md5'
  import moment from 'moment'
  import Vue from 'vue'
  import pageBar from '../pageBar/pageBar'
  import {logout, getUnreadMsg, getMsgDialogData, readOneMsg, readAllMsg, editUserPwd} from '@/api/getData'

  export default {
    name: "Header",
    data() {
      var valiOriginalPwd = (rule, val, cal) => {
        if (val === '') {
          cal(new Error('请输入原密码'));
        } else {
          cal();
        }
      };
      var valiNewPwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          if (value === this.myForm.originalPwd) {
            callback(new Error('新密码不能与原密码一致'));
          } else if (this.myForm.confirmPwd !== '') {
            this.$refs.myForm.validateField('confirmPwd');
          }
          callback();
        }
      };
      var valiConfirmPwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入新密码'));
        } else if (value !== this.myForm.newPwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        activeName: '1',
        msgPageObj: {
          pageNo: 1,
          pageSize: 8,
          pageNum: 0,
        },
        openIndex: -1, // 当前查看公告index
        num: 20,
        role: '',
        openObj: ['open', 'animated', 'fadeIn'],
        closeSrc: '/static/img/header/closeBlue.png', // 消息对话框 关闭按钮图片路径
        dialogUserInfoFormVisible: false,
        dialogMsgFormVisible: false,
        actionUrl: '',
        loginTime: '',
        lastLoginTime: '',
        readed: true,
        msgAlCheck: false, //全部标记已读
        username: '',
        // 账户信息修改表单数据
        myForm: {
          originalPwd: '',
          newPwd: '',
          confirmPwd: '',
        },
        msgList: [],
        rules: {
          newPwd: [
            {validator: valiNewPwd, trigger: 'blur'}
          ],
          confirmPwd: [
            {validator: valiConfirmPwd, trigger: 'blur'}
          ],
          originalPwd: [
            {validator: valiOriginalPwd, trigger: 'blur'}
          ]
        },
        // 消息数据
        unReadNum: 0,
        allMsgNum: 0,
        openId: 0,
        noMsgText: '加载中...',
        noMsg: false,
      }
    },
    components: {
      pageBar
    },
    mounted() {
      this.getUnreadNum();
    },
    created() {
      const arr = [
        {
          value: 0,
          label: '普通用户'
        }, {
          value: 1,
          label: '管理员'
        }, {
          value: 2,
          label: '组织的系统管理员'
        }, {
          value: 3,
          label: '平台管理员'
        }, {
          value: 4,
          label: '系统管理员'
        }
      ]
      const userRole = Number(com.getStore('role'))
      arr.map((val) => {
        if (userRole === val.value) {
          this.role = val.label
          return
        }
      })
      const lastLoginTime = com.getStore('lastLoginTime');
      this.lastLoginTime = lastLoginTime === 'null' ? '' : moment.unix(lastLoginTime / 1000).format('YYYY-MM-DD hh:mm:ss');
      let login = parseInt(com.getStore('loginTime'));
      this.loginTime = com.formatDate(login);
      this.companyName = com.getStore('companyName');
      this.username = com.getStore('username');
    },
    watch: {
      allMsgNum: function (vl) {
        this.msgPageObj.pageNum = vl;
      }
    },

    methods: {
      // 登出
      loginout() {
        this.$confirm('确定退出登录吗?', '退出确定', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          logout().then((res) => {
            location.href = `${com.domain}/login`
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          });
        });
      },
      // // 图片上传状态
      // handleUpImgStatus(res, file) {
      //   if (file.status == 'success') {
      //     this.myForm.image = `${com.uploadUrl}` + res.data;
      //   } else {
      //     this.$message.error('上传图片失败！');
      //   }
      // },
      //
      // // 图片上传的校验
      // beforUpload(file) {
      //   const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
      //   const isLt5 = file.size / 1024 / 1024 < 5;
      //
      //   if (!isRightType) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      //   }
      //   if (!isLt5M) {
      //     this.$message.error('上传头像图片大小不能超过 5MB!');
      //   }
      //   return isRightType && isLt5M;
      // },

      // 获取未读消息数量
      getUnreadNum() {
        getUnreadMsg({}).then((res) => {
          this.unReadNum = res.data.data;
        }).catch((err) => {
          this.$message.error(err.data.message);
        })
      },

      // 获取消息通知数据
      showMsg() {
        this.msgAlCheck = false;
        this.noMsg = false;
        this.noMsgText = '加载中...';
        this.dialogMsgFormVisible = true;
        getMsgDialogData({pageNo: this.msgPageObj.pageNo, pageSize: this.msgPageObj.pageSize}).then((res) => {
          const msgType = {1: '待办任务', 2: '任务反馈', 3: '系统消息'};
          let info = res.data.data;
          let infoArr = info.data;
          var today = {};
          var _today = moment();
          today.year = _today.format('YYYY');
          /*现在的年*/
          today.date = _today.format('YYYY-MM-DD');
          /*现在的时间*/
          today.yesterday = _today.subtract(1, 'days').format('YYYY-MM-DD');
          /*前一天的时间*/
          if (infoArr.length > 0) {
            this.noMsg = false;
            infoArr.forEach(function (e, i) {
              e.messageType = msgType[e.messageTypeId];
              // e.createTime = com.formatDate(e.createTime);
              if (e.createTime.substring(0, 10) === today.date) {
                e.createTime = e.createTime.substring(10, 16)
              } else if (e.createTime.substring(0, 10) === today.yesterday) {
                e.createTime = '昨天' + e.createTime.substring(10, 16)
              } else if (e.createTime.substring(0, 4) === today.year) {
                e.createTime = e.createTime.substring(5, 10);
              } else {
                e.createTime = e.createTime.substring(0, 10);
              }
            })
            this.allMsgNum = info.totalRecord;
            this.msgList = infoArr;
            this.getUnreadNum();
          } else {
            this.noMsg = true;
            this.noMsgText = '暂无消息';
          }
        }).catch((err) => {
          this.dialogMsgFormVisible = true;
          this.noMsg = true;
          this.noMsgText = err.data.message;
        })
      },

      // 修改密码表单提交前校验
      submitDialogForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let reqParam = {};
            reqParam.originalPwd = md5(this.myForm.originalPwd);
            reqParam.newPwd = md5(this.myForm.newPwd);
            this.editUserPwd(reqParam)
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      // 修改用户密码
      editUserPwd(reqParam) {
        editUserPwd(reqParam).then((res) => {
          com.mask()
          this.$message.success({
            message: '操作成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              location.href = `${com.domain}/login`
            }
          })
        }).catch((err) => {
          this.$message.error('操作失败' + err.data.message);
        })
      },

      // 通知提示框 关闭按钮
      closeEnter() {
        this.closeSrc = '/static/img/header/closeWhite.png'
      },
      closeLeave() {
        this.closeSrc = '/static/img/header/closeBlue.png'
      },

      // 消息翻页
      changePageNo(val) {
        this.msgPageObj.pageNo = val;
        this.showMsg();
      },

      // 将消息设置为已读
      readMsg(index, resid, ressta) {
        this.openIndex = index === this.openIndex ? -1 : index;
        const isread = ressta === 0 ? 1 : ressta;
        if (ressta === 0) {
          readOneMsg({messageId: resid, readstate: ressta}).then((res) => {
            for (const i of this.msgList) {
              if (i.messageId == resid) {
                i.readstate = isread;
              }
            }
            this.getUnreadNum();
          }).catch((err) => {
            this.$message.error('操作失败' + err.data.message);
          })
        }
      },

      // 全部标记已读
      msgCheckAll() {
        if (this.unReadNum !== 0) {
          this.$confirm('确定将消息全部标记为已读状态吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            readAllMsg({}).then((res) => {
              this.showMsg()
            })
          }).catch(() => {
            this.msgAlCheck = false;
          });
        } else {
          this.$message.warning('暂无未读消息');
          this.msgAlCheck = false;
        }
      }
    }
  }

  // 弹窗拖拽
  Vue.directive('dialogDrag', {
    bind(el, binding, vnode, oldVnode) {
      const dialogHeaderEl = el.querySelector('.el-dialog__header')
      const dragDom = el.querySelector('.el-dialog')
      dialogHeaderEl.style.cursor = 'move'

      // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null)
      const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)

      dialogHeaderEl.onmousedown = (e) => {
        // 鼠标按下，计算当前元素距离可视区的距离
        const disX = e.clientX - dialogHeaderEl.offsetLeft
        const disY = e.clientY - dialogHeaderEl.offsetTop

        // 获取到的值带px 正则匹配替换
        let styL, styT

        // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
        if (sty.left.includes('%')) {
          styL = +document.body.clientWidth * (+sty.left.replace(/%/g, '') / 100)
          styT = +document.body.clientHeight * (+sty.top.replace(/%/g, '') / 100)
        } else {
          styL = +sty.left.replace(/px/g, '')
          styT = +sty.top.replace(/px/g, '')
        }
        document.onmousemove = function (e) {

          // 通过事件委托，计算移动的距离
          let l = e.clientX - disX
          let t = e.clientY - disY

          // 移动当前元素
          dragDom.style.left = `${l + styL}px`
          dragDom.style.top = `${t + styT}px`
          // 将此时的位置传出去 binding.value({x:e.pageX,y:e.pageY})
        }
        document.onmouseup = function (e) {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    }
  })

  // v-dialogDragWidth: 弹窗宽度拖大 拖小
  Vue.directive('dialogDragWidth', {
    bind(el, binding, vnode, oldVnode) {
      const dragDom = binding.value.$el.querySelector('.el-dialog')

      el.onmousedown = (e) => {
        // 鼠标按下，计算当前元素距离可视区的距离
        const disX = e.clientX - el.offsetLeft

        document.onmousemove = function (e) {
          e.preventDefault() // 移动时禁用默认事件

          // 通过事件委托，计算移动的距离
          const l = e.clientX - disX
          dragDom.style.width = `${l}px`
        }

        document.onmouseup = function (e) {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    }
  })
</script>

<style lang="scss" type="text/scss">
  @import "header";
</style>
